#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :crud.py
# @Time      :2021/6/21 16:50
# @Author    : 刘广鸿


from sqlalchemy.orm import Session
from dbs import model
from dbs import schemas
from json import dumps, loads
from time import time
import hashlib

# from until.mydate import getYesterday

"""新用户注册"""


def create_user(db: Session, user: schemas.UserCreate):
    ret = query_user(db, user.username)
    if ret:
        return False
    else:
        device = "[]"
        u = model.Users(username=user.username, password=user.password, devices=device)
        db.add(u)
        db.commit()
        return True


"""检查用户是否存在"""


def query_user(db: Session, username: str):
    return db.query(model.Users).filter(model.Users.username == username).first()


"""
    更新密码
"""


def UpdatePassword(db: Session, usr_name: str, token: str, oldp: str, newp: str):
    ret = query_user(db, usr_name)
    if not ret.token != token:
        return 0
    else:
        if ret.password != oldp:
            return 0
        db.query(model.Users).filter(model.Users.username == usr_name).update({model.Users.password: newp})
        db.commit()
        return 1


"""
    更新登录状态
"""


def updateUsrState(db: Session, usr_name: str, token: str):
    db.query(model.Users).filter(model.Users.username == usr_name).update({model.Users.token: token})
    return db.commit()


"""
    登录查询接口
"""


def login(db: Session, usr_name: str, password: str):
    usr = query_user(db, usr_name)
    if not usr:
        return 0
    if usr.password == password:
        usr.token = hashlib.md5(b'smartHome_Byzx').hexdigest() + str(int(time()))
        updateUsrState(db, usr_name, usr.token)
        return usr.token


"""
    校验token
"""


def check_token(db: Session, username: str, token: str):
    return db.query(model.Users).filter(model.Users.username == username).first().token == token


"""创建新设备"""


def create_devices(db: Session, username: str, token: str, devices: schemas.DeviceCreate):
    user = db.query(model.Users).filter(model.Users.username == username).first()
    if user.token != token:

        return False
    else:
        dev = model.Devices(uuid=devices.uuid,
                            type=devices.type,
                            name=devices.name,
                            note=devices.note,
                            device_key=devices.devices_key
                            )
        db.add(dev)
        devlist = loads(user.devices)
        devlist.append(devices.uuid)
        db.query(model.Users).filter(
            model.Users.username == username).update(
            {
                model.Users.devices: dumps(devlist)
            }
        )
        db.commit()
    return True


"""绑定设备"""


def bind_devices(db: Session, bindDevice: schemas.BindDevice):
    user = db.query(model.Users).filter(
        model.Users.username == bindDevice.username).first()
    if user.token != bindDevice.token:
        return False
    else:
        devlist = loads(user.devices)
        if bindDevice.uuid in devlist:
            return False
        else:
            devlist.append(bindDevice.uuid)
            db.query(model.Users).filter(
                model.Users.username == bindDevice.username).update(
                {
                    model.Users.devices: dumps(devlist)
                }
            )
            db.commit()
            return True


"""查询单个设备信息"""


def query_device(db: Session, uuid: str):
    return db.query(model.Devices).filter(model.Devices.uuid == uuid).first()


"""查询设备列表"""


def query_devices(db: Session, username: str, token: str):
    user = db.query(model.Users).filter(model.Users.username == username).first()
    if user.token != token:
        return False
    devlist = loads(user.devices)
    devlists = []
    for uuid in devlist:
        devlists.append(query_device(db, uuid))
    return devlists


"""上传数据"""


def create_datas(db: Session, Datas: schemas.DatasBase):
    if not db.query(model.Devices).filter(model.Devices.uuid == Datas.device).first():
        return False
    else:
        datatype = None
        if Datas.dataType == "data":
            datatype = 0
        elif Datas.dataType == "state":
            datatype = 1
        datas = model.Datas(type=datatype, value=Datas.value,
                            identifier=Datas.id, datetime=Datas.datetime,
                            deviceid=Datas.device
                            )
        db.add(datas)
        db.commit()


"""获取设备数据集"""


def query_datas(db: Session, username: str, token: str, uuid: str, offset: int = 0, limit: int = 30):
    if db.query(model.Users).filter(model.Users.username == username
                                    ).first().token != token:
        return False
    else:
        return db.query(model.Datas).filter(model.Datas.deviceid == uuid).offset(offset).limit(limit).all()



